﻿using Cysharp.Threading.Tasks;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public static partial class Extensions
{
    private const string PREFAB_ROOT_PATH = "Sprites/{0}.png";
    private static AssetCache<string, Sprite> s_SpriteAssetCaches = new AssetCache<string, Sprite>(PREFAB_ROOT_PATH);

    public static async UniTask LoadSpriteAsync(this Image image, string spriteName, string fallback = null, bool setNativeSize = false)
    {
        image.enabled = false;
        image.sprite = null;
        if (string.IsNullOrEmpty(spriteName)) return;
        var sprite = await s_SpriteAssetCaches.LoadAsync(spriteName);
        if (sprite == null && !string.IsNullOrEmpty(fallback))
        {
            sprite = await s_SpriteAssetCaches.LoadAsync(fallback);
        }
        if (image == null) return;
        image.sprite = sprite;
        if (image.sprite != null)
        {
            image.enabled = true;
            if (setNativeSize)
            {
                image.SetNativeSize();
            }
        }
        else
        {
            image.enabled = false;
        }
    }

    /// <summary>
    /// 加载 sprite 资源，需要资源存在于 Addressable/Sprites/ 路径下
    /// </summary>
    public static void LoadSprite(this Image image, string spriteName, string fallback = null, bool setNativeSize = false)
    {
        LoadSpriteAsync(image, spriteName, fallback, setNativeSize).Forget();
    }

    public static async UniTask LoadSpriteAsync(this SpriteRenderer spriteRenderer, string spriteName, string fallback = null)
    {
        spriteRenderer.sprite = await s_SpriteAssetCaches.LoadAsync(spriteName);
        if (spriteRenderer.sprite == null && !string.IsNullOrEmpty(fallback))
        {
            spriteRenderer.sprite = await s_SpriteAssetCaches.LoadAsync(fallback);
        }
    }

    public static void LoadSprite(this SpriteRenderer spriteRenderer, string spriteName, string fallback = null)
    {
        LoadSpriteAsync(spriteRenderer, spriteName, fallback).Forget();
    }
}
